/*
 * @Author: zs.duan
 * @Date: 2023-04-05 12:05:53
 * @LastEditors: zs.duan
 * @LastEditTime: 2023-04-09 13:12:01
 * @FilePath: \serve\routes\index.js
 */
var express = require("express");
var router = express.Router();
const Db = require("../utils/db");
const createSql = require("../utils/Create_SQL");
const createSqlv2 = require("../utils/createsql-v2.0.0");
const path = require('path');
const fs = require('fs');
const $errorCode = require('../config/config').errorCode;
const $successCode = require('../config/config').successCode;
const $config = require('../config/config').config;
const setTime = require("../utils/time"); //处理传过来的时间
let request = require("request");
const utils = require("../utils/utils");

/**获取资源文件信息*/
router.get("/views/:path/:fileName", async function (req, res, next) {
    // 获取相对目录
    let paths = req.params.path;
    // 获取文件名
    let fileName = req.params.fileName;
    // 获取文件路径
    let filePath = path.join(__dirname, '../views') + "/" + paths + "/" + fileName;
    // 读取文件
    res.sendFile(filePath);
})
/**获取静态文件资源信息*/
router.get("/views/:path/:path1/:fileName", async function (req, res, next) {
    let filePath = path.join(__dirname, '../views') + "/" + req.params.path + "/" + req.params.path1 + "/" + req.params.fileName;
    res.sendFile(filePath);
})

/**公共处理是否显示*/
async function getShow(type, res) {
    let sql = createSql.select().from("admin_user_menu").where(`is_show = 1 AND pageUrl = '${type}' AND is_del != 1`).end();
    let select = await Db.query(sql);
    if (!select[0]) {
        return false
    }
    if (!select[0].is_show) {
        return false
    }
    return true;
}

/**获取博客标题*/
const getBlogTitle = async () => {
    let show = await getShow("set-title");
    if (!show) {
        return {};
    };
    let sql = createSql.select().from("blog_title_brfie").where("is_show != 0 AND is_del != 1").end();
    let select = await Db.query(sql);
    if (select.code == 10014) {
        return {};
    }
    if (select.length == 0) {
        return {
            title: "我的博客",
            brfie: "欢迎来到我的博客"
        }
    }
    return select[0];
}

/**获取博客导航*/
const getBlogNav = async () => {
    let show = await getShow("set-nav");
    if (!show) {
        return [];
    };
    let sql_1 = createSql.select().from("web_menu").where("pid = '' AND is_show = 1 AND is_del != 1").order("sorts").end();
    let arr_1 = await Db.query(sql_1);
    if (arr_1.code == 10014) return [];
    let sql_2 = createSql.select().from("web_menu").where("pid != '' AND is_show = 1 AND is_del != 1").order("sorts").end();
    let arr_2 = await Db.query(sql_2);
    if (arr_2.code == 10014) return [];
    if (arr_1.code == 10014 || arr_2.code == 10014) return [];
    arr_1.forEach((v) => {
        v.list = [];
        delete v.addtime;
        delete v.is_show;
        delete v.sorts;
        delete v.p_id;
    });
    arr_2.forEach((v) => {
        delete v.addtime;
        delete v.is_show;
        delete v.sorts;
        arr_1.forEach((o) => {
            if (o.ID == v.pid) {
                o.list.push(v);
            }
        });
        delete v.p_id;
    });
    return arr_1;
}

/**获取顶部图*/
const getTopImg = async () => {
    let sql = createSql.select().from("top_img").where("is_show = 1 AND is_del != 1").end();
    let select = await Db.query(sql);
    if (select.code == 10014) return {};
    if (!select.length) {
        return {}
    }
    let json = select[0];
    delete json.addtime;
    delete json.is_show;
    json.image_url = $config.httpImgUrl + json.image_url;
    return json;
}

/**获取友情链接*/
const getFriendLink = async () => {
    let show = await getShow("links");
    if (!show) {
        return [];
    }
    let sql = createSql.select().from("friendly_links").where("is_show = 1 AND is_del != 1").end();
    let select = await Db.query(sql);
    select.forEach(v => {
        delete v.addtime;
        delete v.is_show
    })
    return select;
}
/**计算运行时间和当前年份*/
const getRunTime = () => {
    let date = new Date();
    let year = date.getFullYear();
    let mouth = date.getMonth() + 1;
    let day = date.getDate();
    let days = new Date(year + "-" + mouth + "-" + day) - new Date("2021-08-05");
    return {
        year,
        days: Math.floor(days / 1000 / 60 / 60 / 24) + 1
    }
}

/**获取文章列表*/
const getArticleList = async (page, pageSize) => {
    let show = await getShow("set-article");
    if (!show) {
        return [];
    }
    page = page - 1 || 0;
    pageSize = pageSize || 5;
    let sql = createSql.select().from("article_view").where("is_show != 0 AND is_del != 1").limit(`${pageSize * page},${pageSize}`).end();
    let select = await Db.query(sql);
    select.forEach(async v => {
        v.addtime = setTime.getTime(v.addtime).slice(0, 10);
        if (v.imgUrl) {
            v.imgUrl = $config.httpImgUrl + v.imgUrl
        }
    })
    return select;
}

/**
 * 获取文章数量
 * @param {string} [typeID] 文章类型
 * */
const getArticleCount = async (typeID) => {
    let sql = "";
    sql = createSql.select("COUNT(*) as num").from("article_view").where("is_show != 0 AND is_del != 1").end();
    if (typeID) {
        sql = createSql.select("COUNT(*) as num").from("article_view").where(`is_show != 0 AND is_del != 1 AND typeID = '${typeID}'`).end();
    }
    let data = await Db.query(sql);
    if (data.code == 10014) return 0;
    return data[0].num;
}

/**查询用户信息*/
const getUserInfo = async () => {
    let show = await getShow("user-info");
    if (!show) {
        return {};
    }
    let sql = createSql.select().from("my_userinfo").where("is_show = 1 AND is_del != 1").end();
    let data = await Db.query(sql);
    if (data.code == 10014) return {};
    if (!data.length) {
        return {}
    }
    let json = data[0];
    delete json.addtime;
    delete json.is_show;
    delete json.tel;
    json.usericon = $config.httpImgUrl + json.usericon;
    json.wx = $config.httpImgUrl + "img/wx.png";
    json.wxicon = $config.httpImgUrl + "img/weixin.png";
    json.yxicon = $config.httpImgUrl + "img/youxiang.png";
    json.addressicon = $config.httpImgUrl + "img/address.png";
    json.wxApplet = $config.httpImgUrl + "img/Applet.jpg";
    json.wxAppleticon = $config.httpImgUrl + "img/Appleticon.png";
    return json;
}

/**查询我的标签*/
const getMyTag = async () => {
    let show = await getShow("label");
    if (!show) {
        return [];
    }
    let sql = createSql.select().from("my_label").where("is_del != 1").end();
    let data = await Db.query(sql);
    if (data.code == 10014) return [];
    data.forEach(v => {
        delete v.addtime;
        delete v.is_show;
        delete v.is_del;
    })
    return data;
}

// 获取微薄热搜
const getHotSearch = async () => {
    let show = await getShow("weibo");
    if (!show) {
        return [];
    }
    let wbrsPath = path.resolve(__dirname, "../public/data/wbrs.json");
    var wbrsData = fs.readFileSync(wbrsPath, "utf8");
    let falge = false;
    if (wbrsData) {
        try {
            wbrsData = JSON.parse(wbrsData);
            let timestamp = new Date().getTime();
            if (((timestamp - wbrsData.time) / (10 * 1000)) < 10) {
                falge = true;
            }
        } catch (err) {
            falge = false;
        }
    }
    if (falge) return wbrsData.data.slice(0, 10);
    return new Promise((resolve, reject) => {
        request({
            url: "https://weibo.com/ajax/side/hotSearch",
            headers: {
                referer: "https://weibo.com/hot/search"
            }
        }, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                let reqData = JSON.parse(body).data;
                if (!reqData) {
                    resolve([]);
                    return;
                }
                let sendData = [];
                sendData.push({
                    name: reqData.hotgov?.word,
                    icon_desc: reqData.hotgov?.icon_desc,
                    icon_desc_color: reqData.hotgov?.icon_desc_color,
                    url: reqData.hotgov?.url,
                    id: 1,
                    num: "正能量"
                })
                let i = 1;
                reqData.realtime.forEach(v => {
                    if (v.icon_desc != '商') {
                        let json = {
                            name: v.word,
                            icon_desc: v.icon_desc,
                            icon_desc_color: v.icon_desc_color,
                            url: "https://s.weibo.com/weibo?q=" + v.word,
                            num: v.num,
                            id: i + 1
                        }
                        i++;
                        sendData.push(json);
                    }
                })
                fs.writeFile(wbrsPath, JSON.stringify({ code: 200, msg: "获取成功", data: sendData, time: new Date().getTime() }), "utf8", (err) => {
                    if (err) throw err;
                });
                // 返回前10条数据
                resolve(sendData.slice(0, 10));
            } else {
                resolve([]);
            }
        })
    })
}

/**获取轮播图*/
const getBanner = async () => {
    let show = await getShow("set-banner");
    if (!show) {
        return [];
    }
    let sql = createSql.select().from("banner").where("is_show != 0 AND is_del != 1").order("sorts").end();
    let data = await Db.query(sql);
    if (data.code == 10014) return [];
    data.forEach(v => {
        delete v.addtime;
        delete v.is_show;
        delete v.is_del;
        v.is_text = v.is_text == '1' ? true : false;
        v.ImgUrl = v.is_text ? "" : `${$config.httpImgUrl}${v.ImgUrl}`;
        v.path = v.path ? decodeURIComponent(v.path) : '';
        v.mpPath = v.mpPath ? decodeURIComponent(v.mpPath) : '';
        v.title = v.title.replace(/；/g, "，");
        v.list = v.title.split("，");
    });
    return data;
}

/* GET home page. */
router.get("/", async function (req, res, next) {
    let indexHtml = path.resolve(__dirname, "../public/index.html");
    res.sendFile(indexHtml);
    return;
    let page = req.query.page || 1;
    let pageSize = req.query.pageSize || 10;
    let articleCount = await getArticleCount();
    res.render("index", {
        title: "我的博客",
        blogTitle: await getBlogTitle(), // 博客标题
        navList: await getBlogNav(),   // 博客导航
        topImg: await getTopImg(), // 顶部图
        friendLink: await getFriendLink(), // 友情链接
        runTime: getRunTime(), // 运行时间
        articleList: await getArticleList(page, pageSize), // 文章列表
        page: (Number(page)) * Number(pageSize) < articleCount ? Number(page) + 1 : 0, // 当前页码
        userInfo: await getUserInfo(), // 用户信息
        lableList: await getMyTag(), // 我的标签
        wbrsList: await getHotSearch(), // 微博热搜
        bannerList: await getBanner(), // 轮播图
    });
});

/**
 * 通过ID获取文章详情
 * @param {String} ID
 * */
const getArticleDetailsById = async (ID) => {
    let sql = createSql.select().from("my_article").where(`is_show != 0 AND is_del != 1 AND ID = '${ID}'`).end();

    let data = await Db.query(sql);
    if (data.code == 10014) return {};
    if (data.length) {
        let upsql = createSql.update("my_article").set({ reading: data[0].reading + 1 }).where(`ID = '${ID}'`).end();
        await Db.query(upsql);
        data[0].addtime = setTime.getTime(data[0].addtime);
    }
    return data[0];
}

/**获取文章页面*/
router.get("/article/:id", async function (req, res, next) {
    res.render("article-details/article-details", {
        title: "文章详情",
        blogTitle: await getBlogTitle(), // 博客标题
        navList: await getBlogNav(),   // 博客导航
        friendLink: await getFriendLink(), // 友情链接
        runTime: getRunTime(), // 运行时间
        lableList: await getMyTag(), // 我的标签
        wbrsList: await getHotSearch(), // 微博热搜
        userInfo: await getUserInfo(), // 用户信息
        articleData: await getArticleDetailsById(req.params.id), // 文章详情
    });
})


/**
 * 根据分类id查询文章以及文章名称
 * @param {String} id
 * */
const getArticleListByClassId = async (id, page, pageSize) => {
    pageSize = pageSize || 5;
    page = page - 1 || 0;
    let sql = createSql.select().from("article_view").where(`typeID = '${id}' AND is_show = 1 AND is_del != 1`).limit(`${pageSize * page},${pageSize}`).end();
    let data = await Db.query(sql);
    if (data.code == 10014) return [];
    data.forEach(v => {
        v.addtime = setTime.getTime(v.addtime).slice(0, 10);;
        v.imgUrl = v.imgUrl ? `${$config.httpImgUrl}${v.imgUrl}` : "";
    })
    return data
}

/**
 * 根据分类id查询分类名称
 * @param {String} id
 * */
const getClassNameById = async (id) => {
    let sql = createSql.select("title").from("web_menu").where(`ID = '${id}'`).end();
    let data = await Db.query(sql);
    if (data.code == 10014) return "";
    return data[0].title;
}



/**根据分类id查询页面*/
router.get("/moreArticle/:id", async function (req, res, next) {
    let page = req.query.page || 1;
    let pageSize = req.query.pageSize || 5;
    let articleCount = await getArticleCount(req.params.id);
    res.render("more-article/more-article", {
        title: await getClassNameById(req.params.id),
        blogTitle: await getBlogTitle(), // 博客标题
        navList: await getBlogNav(),   // 博客导航
        friendLink: await getFriendLink(), // 友情链接
        runTime: getRunTime(), // 运行时间
        lableList: await getMyTag(), // 我的标签
        wbrsList: await getHotSearch(), // 微博热搜
        userInfo: await getUserInfo(), // 用户信息
        articleList: await getArticleListByClassId(req.params.id, page, pageSize), // 文章列表
        moreArticleList: await getArticleList(), // 文章列表
        page: (Number(page)) * Number(pageSize) < articleCount ? Number(page) + 1 : 0, // 当前页码
    });
})

/**
 * @swagger
 * /api/index/getNav:
 *    get:
 *      tags:
 *      - 公共接口
 *      summary: 获取nav
 *      produces:
 *      - application/json
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/api/index/getNav", async function (req, res, next) {
    res.send({
        ...$successCode[200],
        data: await getBlogNav()
    })
})

/**
 * @swagger
 * /api/index/getBlogTitle:
 *    get:
 *      tags:
 *      - 公共接口
 *      summary: 获取博客标题与简介
 *      produces:
 *      - application/json
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/api/index/getBlogTitle", async function (req, res, next) {
    res.send({
        ...$successCode[200],
        data: await getBlogTitle()
    })
})

/**
 * @swagger
 * /api/index/getTopImg:
 *    get:
 *      tags:
 *      - 公共接口
 *      summary: 获取顶部图
 *      produces:
 *      - application/json
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/api/index/getTopImg", async function (req, res, next) {
    res.send({
        ...$successCode[200],
        data: await getTopImg()
    })
})

/**
 * @swagger
 * /api/index/getBanner:
 *    get:
 *      tags:
 *      - 公共接口
 *      summary: 获取banner
 *      produces:
 *      - application/json
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/api/index/getBanner", async function (req, res, next) {
    res.send({
        ...$successCode[200],
        data: await getBanner()
    })
})

/**
 * @swagger
 * /api/article/getArticleAll:
 *    get:
 *      tags:
 *      - 公共接口
 *      summary: 获取根据页码获取文章列表
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: page
 *          in: query
 *          description: 页码
 *          required: true
 *          type: string
 *        - name: pageSize
 *          in: query
 *          description: 每页条数
 *          required: true
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/api/article/getArticleAll", async function (req, res, next) {
    let page = req.query.page || 1;
    let pageSize = req.query.pageSize || 5;
    let articleCount = await getArticleCount();
    res.send({
        ...$successCode[200],
        data: {
            data: await getArticleList(page, pageSize), // 文章列表
            count: articleCount, // 文章数量
        }
    })
})

/**
 * @swagger
 * /api/article/getArticleById:
 *    get:
 *      tags:
 *      - 公共接口
 *      summary: 获取根据id获取文章详情
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: ID
 *          in: query
 *          description: 文章id
 *          required: true
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/api/article/getArticleById", async function (req, res, next) {
    let pass = utils.detectSQL(req.query.ID);
    if (!pass) {
        res.status(500);
        return res.json(
            $errorCode[10020]
        )
    }
    res.send({
        ...$successCode[200],
        data: await getArticleDetailsById(req.query.ID)
    })
})

/**
 * @swagger
 * /api/article/getArticleByClassifyId:
 *    get:
 *      tags:
 *      - 公共接口
 *      summary: 获取根据分类id获取文章列表
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: ID
 *          in: query
 *          description: 文章id
 *          required: true
 *          type: string
 *        - name: page
 *          in: query
 *          description: 页码
 *          required: true
 *          type: string
 *        - name: pageSize
 *          in: query
 *          description: 每页条数
 *          required: true
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/api/article/getArticleByClassifyId", async function (req, res, next) {
    let pass = utils.detectSQL(req.query.ID);
    if (!pass) {
        res.status(500);
        return res.json(
            $errorCode[10020]
        )
    }
    let page = req.query.page || 1;
    let pageSize = req.query.pageSize || 5;
    let articleCount = await getArticleCount(req.query.ID);
    res.send({
        ...$successCode[200],
        data: {
            data: await getArticleListByClassId(req.query.ID, page, pageSize), // 文章列表
            count: articleCount, // 文章数量
        }
    })
})


/**
 * @swagger
 * /api/index/getMyUserInfo:
 *    get:
 *      tags:
 *      - 公共接口
 *      summary: 获取个人信息
 *      produces:
 *      - application/json
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/api/index/getMyUserInfo", async function (req, res, next) {
    res.send({
        ...$successCode[200],
        data: await getUserInfo()
    })
})

/**
 * @swagger
 * /api/index/getMyLable:
 *    get:
 *      tags:
 *      - 公共接口
 *      summary: 获取我的标签
 *      produces:
 *      - application/json
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/api/index/getMyLable", async function (req, res, next) {
    res.send({
        ...$successCode[200],
        data: await getMyTag()
    })
})

/**
 * @swagger
 * /api/index/getLink:
 *    get:
 *      tags:
 *      - 公共接口
 *      summary: 获取友情链接
 *      produces:
 *      - application/json
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/api/index/getLink", async function (req, res, next) {
    res.send({
        ...$successCode[200],
        data: await getFriendLink()
    })
})

/**
 * @swagger
 * /api/index/search:
 *    get:
 *      tags:
 *      - 公共接口
 *      summary: 搜索
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: q
 *          in: query
 *          description: 搜索内容
 *          required: true
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/api/index/search", async function (req, res, next) {
    let q = req.query.q;
    let pass = utils.detectSQL(q);
    if (!pass) {
        return res.json(
            $errorCode[10020]
        )
    }
    if (!q) return res.send($errorCode[10003]);
    let sql = "";
    sql = createSql.select().from("search_settings").where(`title = '${q}' AND is_show = 1 AND is_del != 1`).end();
    let data = await Db.query(sql);
    if (data.code) return;
    let first = data[0];
    if (first) {
        if (first.is_stop) {
            return res.send({
                ...$errorCode[10000],
                message: "该搜索关键词已被禁用"
            })
        }
        if (first.is_activity) {
            return res.send({
                ...$successCode[200],
                data: first,
            })
        }
    }
    sql = createSql.select().from("article_view").where(`title LIKE '%${q}%' OR brfie LIKE '%${q}%'  AND is_show != 0 AND is_del != 1`).end();
    data = await Db.query(sql);
    if (data.code == 10014) return [];
    data.forEach(v => {
        v.addtime = setTime.getTime(v.addtime).slice(0, 10);;
        v.imgUrl = v.imgUrl ? `${$config.httpImgUrl}${v.imgUrl}` : "";
    })
    return res.send({
        ...$successCode[200],
        data: {
            data,
        }
    })
})

/**
 * @swagger
 * /api/index/getHotSearch:
 *    get:
 *      tags:
 *      - 公共接口
 *      summary: 获取微博热搜
 *      produces:
 *      - application/json
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/api/index/getHotSearch", async function (req, res, next) {
    res.send({
        ...$successCode[200],
        data: await getHotSearch()
    })
})

/**
 * @swagger
 * /api/index/baiduPush:
 *    post:
 *      tags:
 *      - 百度推送
 *      summary: 百度推送
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: url
 *          in: query
 *          description: 推送的连接 多个url用逗号隔开
 *          required: true
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.post("/api/index/baiduPush", async function (req, res, next) {
    let urls = req.query.url;
    if (!urls) return res.send($errorCode[10003]);
    let pushUrl = urls.split(",").join("\n");
    let url = "http://data.zz.baidu.com/urls?site=https://anran233.com&token=bDlED4qD3smEmx84"
    if (urls.indexOf("https://www.anran233.com") == -1) {
        url = "http://data.zz.baidu.com/urls?site=https://www.anran233.com&token=bDlED4qD3smEmx84"
    }
    request({
        url: url,
        method: "post",
        headers: {
            "Content-Type": "text/plain",
            "Content-Length": pushUrl.length
        },
        body: pushUrl
    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            res.send({
                ...$successCode[200],
                data: body
            })
        } else {
            res.send({
                ...$errorCode[10000],
                message: "推送失败"
            })
        }
    })

})

/**
 * @swagger
 * /api/index/getProtocol:
 *    get:
 *      tags:
 *      - 公共接口
 *      summary: 公共接口-获取协议
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: type
 *          in: query
 *          description: 协议类型
 *          required: true
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/api/index/getProtocol", async function (req, res, next) {
    let type = req.query.type;
    if (!type) return res.send($errorCode[10003]);
    let sql = createSql.select().from("protocol").where(`type = '${type}' AND is_show != 0 AND is_del != 1`).end();
    let data = await Db.query(sql);
    if (data.code == 10014) return res.send($errorCode[10000]);
    data.forEach(item => {
        item.content = decodeURIComponent(item.content) || "";
        item.addtime = item.addtime ? utils.getTime('yyyy-MM-dd HH:mm:ss', item.addtime) : null;
        item.updatetime = item.updatetime ? utils.getTime('yyyy-MM-dd HH:mm:ss', item.updatetime) : null;
    })
    return res.send({
        ...$successCode[200],
        data: data[0]
    })
})

/**
 * @swagger
 * /api/index/setIpLocation:
 *    get:
 *      tags:
 *      - 公共接口
 *      summary: 公共接口-设置ip地址位置信息
 *      produces:
 *      - application/json
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/api/index/setIpLocation", async function (req, res, next) {
    let sql = createSql.select('ip', true).from('actionlog').where("createdTime > '2025-04-23 00:00:00'").build();
    let reslut = await Db.query(sql, res);
    if (reslut.code > 200) return;
    let ipv4_pattern = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])$/;
    let i = 0;

    const getIpLocationAgain = async (time) => {
        // 随机生成 1000 - 3000 的整数
        let random = Math.floor(Math.random() * (3000 - 1000 + 1)) + 1000;
        time ? random = time : random;
        if (random == 0) {
            i++;
            getIpLocation();
            return;
        }
        setTimeout(async () => {
            i++;
            getIpLocation();
        }, random);
    }

    const getIpLocation = async () => {
        if (i >= reslut.length) {
            console.log('处理结束');
            return;
        };
        console.log(`当前进度 ${i}/${reslut.length} , 正在处理ip ${reslut[i].ip}`);
        if (ipv4_pattern.test(reslut[i].ip)) {
            let insetData = {}
            // 取得ip前两位
            let ip = reslut[i].ip.split('.');
            insetData.ipFirst = ip[0] + '.' + ip[1];
            let hasIpSql = createSql.select().from('iplocation').where(`ip = '${reslut[i].ip}'`).build();
            let hasIp = await Db.query(hasIpSql, res);
            if (hasIp.code > 200) {
                getIpLocationAgain(0)
                return;
            }
            if (hasIp.length > 0) {
                console.log("hasIp");
                getIpLocationAgain(0)
                return;
            }
            let hasFirstSql = createSql.select().from('iplocation').where(`ipFirst = '${insetData.ipFirst}'`).build();
            let hasFirst = await Db.query(hasFirstSql);
            if (hasFirst.length > 0) {
                console.log("hasFirst");
                insetData = hasFirst[0];
                insetData.ip = reslut[i].ip;
                insetData.ID = utils.getUuid();
                insetData.createdTime = utils.getTime();
                await Db.query(createSql.insert('iplocation').value(insetData).build(), res);
                getIpLocationAgain(0)
                return;
            }
            let ipLocation = await utils.getIPByLocation(reslut[i].ip);
            let ipdata = ipLocation.ipdata;
            insetData.ip = reslut[i].ip;
            insetData.province = ipdata.info1;
            insetData.city = ipdata.info2;
            insetData.district = ipdata.info3;
            insetData.isp = ipdata.isp;
            insetData.ID = utils.getUuid();
            insetData.createdTime = utils.getTime();
            await Db.query(createSql.insert('iplocation').value(insetData).build(), res)
            console.log("插入新数据", insetData);
            getIpLocationAgain()
        } else {
            getIpLocationAgain(0)
        }
    }
    getIpLocation();
    res.send({
        ...$successCode[200],
        data: {
            message: '已经开始处理'
        }
    })
})


/**
 * @swagger
 * /api/index/getMyAsset:
 *    get:
 *      tags:
 *      - 我的资产
 *      summary: 我的资产-前台用户获取我的资产
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: type
 *          description: 排序方式
 *          in: query
 *          required: false
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/api/index/getMyAsset", async function (req, res, next) {
    let isLogin = {};
    try {
        isLogin = await utils.isUserLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code != 200) return;
    // 通过用户ID 查询 关联的后台ID
    let sql = "";
    sql = createSqlv2().select('admin_user_id').from("web_userInfo")
        .where(`ID = '${isLogin.data.ID}'`).build();
    let adminUser = await Db.query(sql);
    if (!adminUser.length) {
        return res.send({
            ...$successCode[200],
            data: {
                total: 0,
                list: [],
                allPrice: 0
            }
        })
    }
    let orderBy = 'createdtime';
    let type = req.query.type;
    orderBy = type == 'time' ? 'buy_time' : 'createdtime';
    sql = createSqlv2().select().from("my_asset")
        .where(`create_user = '${adminUser[0].admin_user_id}'`)
        .and("is_del = 0")
        .order(orderBy , "desc")
        .build();
    let reslut = await Db.query(sql);
    reslut = utils.formatDateByArray(reslut, ["createdtime", "updatetime", 'buy_time']);
    reslut = utils.deleteArrayObject(reslut, ["is_del"]);
    let allPrice = 0 ;
    // 计算一下还差多少是10元每天
    let break_even_price = 10;
    // 计算每天的价格
    reslut.forEach(item => {
        item.day_count = Math.ceil((new Date().getTime() - new Date(item.buy_time).getTime()) / (24 * 60 * 60 * 1000));
        item.day_price = (item.buy_amount / item.day_count).toFixed(2);
        let day = Number((item.buy_amount / break_even_price).toFixed(2));
        item.day_count_10 = day - item.day_count;
        // 预计回本日期
        item.back_time = utils.formatDate('yyyy年MM月dd', new Date(new Date().getTime() + item.day_count_10 * 24 * 60 * 60 * 1000));
        // 是否回本呢
        item.is_back = item.day_price <= break_even_price;
        if (item.is_back) {
            item.tips = `已于${item.back_time}回本`
        } else {
            item.tips = `预计在${item.day_count_10}天后回本(${item.back_time})`
        }
        item.buy_time = utils.formatDate('yyyy年MM月dd', new Date(item.buy_time));
        allPrice += Number(item.buy_amount);
    });
    if(type == 'day'){
        reslut.sort(function(a,b){
            return b.day_count - a.day_count;
        });
    }
    if(type == 'average_price'){
        reslut.sort(function(a,b){
            return a.day_price - b.day_price;
        });
    }
    if(type == 'price'){
        reslut.sort(function(a,b){
            return Number(b.buy_amount) - Number(a.buy_amount);
        });
    }
    return res.send({
        ...$successCode[200],
        data: {
            list : reslut,
            total: reslut.length,
            allPrice: allPrice,
            backTips : `在每天${break_even_price}元的情况下计算`
        }
    })
})

module.exports = router;
